var River = {
	randomNum: 0,
	stopHover: false,
	support3d: true,
	endOfLine: false,
	echoPre: 'http://api.echoenabled.com/v1/search?q=',
	echoPost: 'itemsPerPage:8+&appkey=prod.umg',
	rFb: {'data': [], 'name': 'facebook'},
	rTw: {'data': [], 'name': 'twitter'},
	rYt: {'data': [], 'name': 'youtube'},
	rPh: {'data': [], 'name': 'photos'},
	rJb: {'data': [], 'name': 'news'},
	rFa: {'data': [], 'name': 'fan'},
	rSt: {'data': [], 'name': 'store'},
	rGif: {'data': [], 'name': 'gifs'},
	rAl: {'data': [], 'name': 'albums'},
	sourceNextPage: {tw: '', fb: '', yt: '', ph: '', fa: '', st: '', jb: ''},
	sourceLoadComplete: {tw: false, fb: false, yt: false, ph: false, fa: false, st: false, jb: false, gf: false, al: false},
	topFiveFan: [],
	sourceArray: [],
	sourceMaxResults: 8,
	sourceOffset: 0,
	sourceOrder: [0, 1, 2, 3, 4, 5, 6, 7, 8],  //These numbers somehow correlate to the sourceLoadComplete array, they must match? TODO:// Investgate further.
	killScroll: true,
	thisYear: new Date().getFullYear(),
	firstTimeLoad: true,
	currentItems: 3,
	mousePos: {x: 0, y: 0},
	riverWidth: 0,
	allowResize: true,
	river: '',
	riverInner: '',
	riverContainer: '',
	filterContainer: '',
	outerContainer: '',
	musicPlayer: '',
	youtubeModule: '',
	youtubeHeight: 0,
	ads: '',
	backToTop: '',
	showBackToTop: true,
	rolloverTimer: 0,
	errorCounter: 0,
	easterEgg: {rolloverCount: 0, timeoutID: -1, discovered: false},

	init: function() {
		this.river = $('#river');
		this.riverInner = $('#riverInner');
		this.filterContainer = $('#filterContainer');
		this.riverContainer = $('#riverContainer');
		this.ads = $('#ads');
		this.musicPlayer = $('#musicPlayer');
		this.backToTop = $('#backToTop');

		$('.aboutPage').bind('click', this.onClickNav);
		$('#pulloutTab').bind('click', this.onClickRiverTab);
		$('.eventsPage').bind('click', this.onClickNav);
		$('.chatPage').bind('click', this.onClickNav);
		$('.loginSocial').bind('click', this.openSocialBar);
		$('.filterMusic').bind('click', this.onClickNav);
		$('.launchModal').live('click', this.launchModal);
		$('.vote-btn').live('click', this.onClickVote);
		$('.externalLink, .externalShareLink').live('click', this.trackExternalNavLink);
		River.riverInner.bind('scroll', this.onScrollToLoadMore);
		$(window).bind('resize', this.onResizeRiver);
		$(window).bind('mousemove', this.onMouseMove);
		River.backToTop.bind('click', this.onBackToTop);

		River.support3d = BrowserDetect.support3d();
		River.river.isotope({
			itemSelector: '.bieber-container, .youtube-module',
			filter: '.all'
		});
		
		this.appliaction = new Echo.Application({
			appkey: "prod.umg",
			"plugins": [{
				"name": "Like" 
			}]
		});

		$("#footer .legal a span").text(River.thisYear);

		Gallery.init();
		Header.init();
		ContentPanel.init();
		Events.init();
		Chat.init();
		About.init();
		if (swfobject.hasFlashPlayerVersion("10.0.0")) {
			Cube.init();
		}
		this.onResizeRiver('init');
		this.loadGifs();
		this.loadAlbums();
		this.loadAllTheThings();
	},

	loadAllTheThings: function() {
		if (River.sourceOffset > 5) {
			River.endOfLine = true;
			$('#loadMore').html('<span>We can\'t go any further, but there\'s lots of great stories above!</span>');
			return;
		}

		var pagedKey = (River.sourceOffset > 0) ? "pageAfter:" : "";
		River.loadTwitterData(pagedKey);
		River.loadFacebookData(pagedKey);
		River.loadYouTubeData(pagedKey);
		River.loadPhotosData(pagedKey);
		River.loadFanData(pagedKey);
		River.loadStoreData(pagedKey);
		River.loadNewsData(pagedKey);
	},

	loadTwitterData: function(pagedKey) {
		Utility.log('Loading tweets.');
		$.ajax({
			url: River.echoPre+'((childrenof:http://www.justinbiebermusic.com/official/Twitter source:Twitter user.id:http://twitter.com/justinbieber -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged)) safeHTML:false children:0 -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged '+pagedKey+' '+River.sourceNextPage.tw+' '+River.echoPost,
			dataType: 'jsonp',
			success: River.onTwitterComplete
		});
	},

	loadFacebookData: function(pagedKey) {
		Utility.log('Loading Facebook posts.');
		$.ajax({
			url: River.echoPre+'((childrenof:http://www.justinbiebermusic.com/official/Facebook source:Facebook user.id:http://facebook.com/justinbieber -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged)) safeHTML:false children:0 -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged safeHTML:aggressive '+pagedKey+' '+River.sourceNextPage.fb+' '+River.echoPost,
			dataType: 'jsonp',
			success: River.onFacebookComplete
		});
	},

	loadYouTubeData: function(pagedKey) {
		Utility.log('Loading videos.');
		$.ajax({
			url: River.echoPre+'((childrenof:http://www.justinbiebermusic.com/official/YouTube source:YouTube (user.id:http://youtube.com/kidrauhl OR user.id:http://youtube.com/justinbiebervevo) -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged)) safeHTML:false children:0 -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged '+pagedKey+' '+River.sourceNextPage.yt+' '+River.echoPost,
			dataType: 'jsonp',
			success: River.onVideosComplete
		});
	},

	loadPhotosData: function(pagedKey) {
		Utility.log('Loading photos.');
		$.ajax({
			url: River.echoPre+'((childrenof:http://www.justinbiebermusic.com/* source:MGCMSPhotos -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged -user.state:ModeratorBanned) OR (childrenof:http://www.justinbiebermusic.com/official/Twitter source:Twitter user.id:http://twitter.com/justinbieber markers:arktan-photo -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged -user.state:ModeratorBanned)) safeHTML:false children:0 -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged -user.state:ModeratorBanned childrenSortOrder:reverseChronological childrenItemsPerPage:0 '+pagedKey+' '+River.sourceNextPage.ph+' '+River.echoPost,
			dataType: 'jsonp',
			success: River.onPhotosComplete
		});
	},
	
	loadFanData: function(pagedKey) {
		Utility.log('Loading fans.');
		$.ajax({
			url: River.echoPre+'((childrenof:http://justinbiebermusic.com/fanfeed/comments)) safeHTML:off state:Untouched,ModeratorApproved -user.state:ModeratorBanned children:0 -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged -user.state:ModeratorBanned childrenSortOrder:reverseChronological childrenItemsPerPage:0 '+pagedKey+' '+River.sourceNextPage.fa+' '+River.echoPost,
			dataType: 'jsonp',
			success: River.onFansComplete
		});
	},
	
	loadStoreData: function(pagedKey) {
		Utility.log('Loading store.');
		$.ajax({
			url: River.echoPre+'((childrenof:http://www.justinbiebermusic.com/official/rss.musictoday.com/basic/bestseller/2181.xml source:rss.musictoday.com -state:ModeratorDeleted,SystemFlagged,CommunityFlagged,ModeratorFlagged -user.state:ModeratorBanned)) safeHTML:false children:1 -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged -user.state:ModeratorBanned childrenSortOrder:reverseChronological childrenItemsPerPage:0 '+pagedKey+' '+River.sourceNextPage.st+' '+River.echoPost,
			dataType: 'jsonp',
			success: River.onStoreComplete
		});
	},

	loadNewsData: function(pagedKey) {
		Utility.log('Loading news posts.');
		$.ajax({
			url: River.echoPre+'((childrenof:http://www.justinbiebermusic.com/* source:www.justinbiebermusic.com -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged)) safeHTML:false children:0 -state:ModeratorDeleted,SystemFlagged,ModeratorFlagged '+pagedKey+' '+River.sourceNextPage.jb+' '+River.echoPost,
			dataType: 'jsonp',
			success: River.onNewsComplete
		});	
	},

	loadGifs: function() {
		$.ajax({
			url: 'js/animatedGifs.html?v=3',
			dataType: 'json',
			success: River.onGifsComplete
		});	
	},

	loadAlbums: function() {
		$.ajax({
			url: 'js/albums.js',
			dataType: 'json',
			success: River.onAlbumsComplete
		});	
	},

	loadYoutubeFanVideos: function() {
		$.ajax({
			url: 'https://gdata.youtube.com/feeds/api/playlists/826524778B77A39B?v=2&start-index=1&max-results=50&alt=jsonc&safeSearch=strict',
			dataType: 'jsonp',
			success: River.onYoutubeFanVideosComplete
		});	
	},

	onFacebookComplete: function(data) {
		if(data.result != undefined && data.result == 'error') {
			if(River.errorCounter < 4) {
				Utility.log('Could not load facebook posts, trying again...');
				setTimeout(function() {
					var pagedKey = (River.sourceOffset > 0) ? "pageAfter:" : "";
					River.errorCounter++;
					River.loadFacebookData(pagedKey);
				}, 3000);
			}
		} else {
			River.rFb.data.push(data.entries);
			River.sourceNextPage.fb = data.nextPageAfter;
			River.sourceLoadComplete.fb = true;
			River.checkServices();
		}
	},

	onNewsComplete: function(data) {
		if(data.result != undefined && data.result == 'error') {
			if(River.errorCounter < 4) {
				Utility.log('Could not load news posts, trying again...');
				setTimeout(function() {
					var pagedKey = (River.sourceOffset > 0) ? "pageAfter:" : "";
					River.errorCounter++;
					River.loadNewsData(pagedKey);
				}, 3000);
			}
		} else {
			River.rJb.data.push(data.entries);
			River.sourceNextPage.jb = data.nextPageAfter;
			River.sourceLoadComplete.jb = true;
			River.checkServices();
		}
	},

	onTwitterComplete: function(data) {
		if(data.result != undefined && data.result == 'error') {
			if(River.errorCounter < 4) {
				Utility.log('Could not load tweets, trying again...');
				setTimeout(function() {
					var pagedKey = (River.sourceOffset > 0) ? "pageAfter:" : "";
					River.errorCounter++;
					River.loadTwitterData(pagedKey);
				}, 3000);
			}
		} else {
			River.rTw.data.push(data.entries);
			River.sourceNextPage.tw = data.nextPageAfter;
			River.sourceLoadComplete.tw = true;
			River.checkServices();
		}
	},

	onPhotosComplete: function(data) {
		if(data.result != undefined && data.result == 'error') {
			if(River.errorCounter < 4) {
				Utility.log('Could not load photos, trying again...');
				setTimeout(function() {
					var pagedKey = (River.sourceOffset > 0) ? "pageAfter:" : "";
					River.errorCounter++;
					River.loadPhotosData(pagedKey);
				}, 3000);
			}
		} else {
			River.rPh.data.push(data.entries);
			River.sourceNextPage.ph = data.nextPageAfter;
			River.sourceLoadComplete.ph = true;
			River.checkServices();
		}
	},
	
	onFansComplete: function(data) {
		if(data.result != undefined && data.result == 'error') {
			if(River.errorCounter < 4) {
				Utility.log('Could not load fans, trying again...');
				setTimeout(function() {
					var pagedKey = (River.sourceOffset > 0) ? "pageAfter:" : "";
					River.errorCounter++;
					River.loadFanData(pagedKey);
				}, 3000);
			}
		} else {
			River.rFa.data.push(data.entries);
			River.sourceNextPage.fa = data.nextPageAfter;
			River.sourceLoadComplete.fa = true;
			River.checkServices();
		}
	},
	
	onStoreComplete: function(data) {
		if(data.result != undefined && data.result == 'error') {
			if(River.errorCounter < 4) {
				Utility.log('Could not load stores, trying again...');
				setTimeout(function() {
					var pagedKey = (River.sourceOffset > 0) ? "pageAfter:" : "";
					River.errorCounter++;
					River.loadStoreData(pagedKey);
				}, 3000);
			}
		} else {
			River.rSt.data.push(data.entries);
			River.sourceNextPage.st = data.nextPageAfter;
			River.sourceLoadComplete.st = true;
			River.checkServices();
		}
	},

	onVideosComplete: function(data) {
		if(data.result != undefined && data.result == 'error') {
			if(River.errorCounter < 4) {
				Utility.log('Could not load videos, trying again...');
				setTimeout(function() {
					var pagedKey = (River.sourceOffset > 0) ? "pageAfter:" : "";
					River.errorCounter++;
					River.loadYouTubeData(pagedKey);
				}, 3000);
			}
		} else {
			River.rYt.data.push(data.entries);
			River.sourceNextPage.yt = data.nextPageAfter;
			River.sourceLoadComplete.yt = true;
			River.checkServices();
		}
	},

	onGifsComplete: function(data) {
		var gifs = [];

		for(var i=1; i <= data.length; i++) {
			gifs.push(data[i]);

			if(i % 8 == 0) {
				River.rGif.data.push(gifs);
				gifs = [];
			}
		}

		River.sourceLoadComplete.gf = true;
		River.checkServices();
	},

	onAlbumsComplete: function(data) {
		var albums = [];
		
		for(var i=1; i <= data.length; i++) {
			albums.push(data[i-1]);

			if(i % 8 == 0) {
				River.rAl.data.push(albums);
				albums = [];
			} else {
				if(i == data.length) {
					River.rAl.data.push(albums);
				}
			}
		}

		River.sourceLoadComplete.al = true;
		River.checkServices();
	},

	onYoutubeFanVideosComplete: function(data) {
		var items = data.data.items;
		River.youtubeHeight = items.length * 85; // Height of one youtube video in module
		var html = '<ul id="youtubeVideos">';

		for(var i=0; i < items.length; i++) {
			html += '<li>'+
					'<a href="http://youtube.com/watch?v='+items[i].video.id+'" class="thumbnail" style="background: url(http://i.ytimg.com/vi/'+items[i].video.id+'/1.jpg) no-repeat 50% 50%;" target="_blank"></a>'+
					'<div class="youtube-content">'+
					'<h3><a href="http://youtube.com/watch?v='+items[i].video.id+'" target="_blank">'+Utility.truncateByWords(items[i].video.title, 7)+'</a></h3>'+
					'<p>'+Utility.truncateByWords(items[i].video.description, 8)+'</p>'+
					//'<p>Views: '+ items[i].viewCount+'</p>'+
					'</div>'+
					'</li>';
		}

		html += '</ul>';

		$('#youtubeSlider').append(html);
		$('#scrollUp').bind('click', River.onYoutubeScrollUp);
		$('#scrollDown').bind('click', River.onYoutubeScrollDown);
	},

	checkServices: function() {	
		for (isComplete in River.sourceLoadComplete) {
			if (River.sourceLoadComplete[isComplete] == false) return;
		}

		if(River.sourceArray.length == 0) {
			River.sourceArray = [River.rTw, River.rFb, River.rYt, River.rPh, River.rFa, River.rSt, River.rJb, River.rGif, River.rAl];
		}

		var n = 0;

		for(i in River.sourceNextPage) {
			var nextPageId = River.sourceNextPage[i];

			if(nextPageId == undefined) {
				River.sourceArray.splice(n, 1);
				var pos = River.sourceOrder.indexOf(River.sourceOrder.length - 1);
				River.sourceOrder.splice(pos, 1);
			}

			n++;
		}

		if(River.firstTimeLoad == true) {
			River.deepLink(document.location.hash);
			River.firstTimeLoad = false;
		}
		
		River.populateRiver();
		River.killScroll = false;
		River.sourceLoadComplete = {tw: false, fb: false, yt: false, ph: false, fa:false, jb: false};
		River.errorCounter = 0;
		//River.resizeContent();
	},

	shuffle: function(o) {
	    for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	    var pos = o.indexOf(5);

		if(pos > -1) {
			o.splice(pos, 1);
	    	o.push(5);
		}

	    return o;
	},

	populateRiver: function() {
		$('#loadMore').html('');
		var ii = 0;
		
		var sourcePos = {};
		
		//Before we populate, make sure that any empty source data is removed.
		for(var n=0; n<River.sourceOrder.length; n++) {
			if(typeof(River.sourceArray[n].data[River.sourceOffset]) == 'undefined' || River.sourceArray[n].data[River.sourceOffset].length == 0) {
				var pos = River.sourceOrder.indexOf(River.sourceOrder.length - 1);
				River.sourceOrder.splice(pos, 1);
				River.sourceArray.splice(n, 1)
			} else {
				sourcePos[ River.sourceArray[n].name] = 0;
			}
		}

		for (var i=0; i<(River.sourceMaxResults * River.sourceOrder.length); i++) {
			var sourceData = '';
			var source = source = River.sourceArray[River.sourceOrder[i%River.sourceOrder.length]].name;
			if(typeof(River.sourceArray[River.sourceOrder[i%River.sourceOrder.length]].data[River.sourceOffset][sourcePos[source]]) == 'undefined') {
				sourceData = '';
			} else {
				source = River.sourceArray[River.sourceOrder[i%River.sourceOrder.length]].name;
				
				if(source == 'gifs' || source == 'albums' || source == 'fan') {
					sourceData = River.sourceArray[River.sourceOrder[i%River.sourceOrder.length]].data[River.sourceOffset][sourcePos[source]];
				} else {
					sourceData = River.sourceArray[River.sourceOrder[i%River.sourceOrder.length]].data[River.sourceOffset][sourcePos[source]].object;
					
				}
			}
			
			sourcePos[source]++;
			
			if(source == 'youtube') {
				Utility.log(sourceData['title'],i%River.sourceOrder.length, River.sourceOrder[i%River.sourceOrder.length]);
			}

		    if(sourceData != '') {
			    var innerContainerCss3 = (River.support3d == true) ? 'inner-container-css3' : '';
			    var side1Css3 = (River.support3d == true) ? 'side-1-css3' : '';
			    var side2Css3 = (River.support3d == true) ? 'side-2-css3' : '" style="display: none; z-index: 10;';

			    if(i == 2 && River.sourceOffset == 0) {
			    	var html = '<div class="youtube-module all"><h2>Fan Videos</h2><div class="youtube-slider" id="youtubeSlider"></div><div class="youtube-module-buttons"><a href="#" class="youtube-scroll-up" id="scrollUp"></a><a href="#" class="youtube-scroll-down" id="scrollDown"></a></div></div>';
			    	var $item = $(html);
					River.river.isotope('insert', $item);
					this.loadYoutubeFanVideos();
			    }

			    switch(source) {	
			    	case "twitter":
			    		var id = sourceData.id;
			    		var tweetID = id.substring(sourceData.id.indexOf('/', 35)+1);
						var published = Utility.prettyDate(sourceData.published);
						var html = '';
						var shareTwitter = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/tweet_button.html?url='+Utility.urlEncode('http://justinbiebermusic.com')+'&amp;text='+Utility.urlEncode(Utility.stripTags(sourceData.title))+'&amp;count=none" class="twitter-button"></iframe>';
						var shareGoogle = '<div class="google-button"><div class="g-plusone" data-size="medium" data-annotation="none" data-href="'+id+'"></div></div>';
						var shareHtml = shareTwitter + shareGoogle;
						var data = {type: 'twitter', shareHtml: shareHtml, shareCount: 2, echoId: id};
						
						//using original imageURL def from image section, will update when we change river
						var imageUrl = $(sourceData.content).eq(1).children().children().children().attr('data-src-full');
						var imageClass = '';

						if(imageUrl == undefined) {
							imageClass = 'empty';
						}
						

						if(River.support3d == true) {
							var extraCss3Html = (River.support3d == true) ? '<div class="side-3-css3"><div class="side-rollover"><p class="rollover-text">'+sourceData.title+'</p><p class="timestamp">'+published+'</p></div></div><div class="side-4-css3"><div class="tweet-thumb ' +imageClass+'"><img src="'+imageUrl+'"/></div><p>'+sourceData.title+'</p></div>' : '';
							html = '<div class="bieber-container all twitter" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3"><div class="tweet-thumb ' +imageClass+'"><img src="'+imageUrl+'"/></div><p>'+sourceData.title+'</p></div><div class="side-2 side-2-css3"><div class="side-rollover"><p class="rollover-text">'+sourceData.title+'</p><p class="timestamp">'+published+'</p></div></div>'+extraCss3Html+'</div></div></div>';
						} else {
							html = '<div class="bieber-container all twitter"><div class="outter-container"><div class="inner-container"><div class="side-1"><div class="tweet-thumb ' +imageClass+'"><img src="'+imageUrl+'"/></div><p>'+sourceData.title+'</p></div><div class="side-2 nocss3d"><div class="tweet-thumb ' +imageClass+'"><img src="'+imageUrl+'"/></div><p class="rollover-text">'+sourceData.title+'</p><p class="timestamp">'+published+'</p></div></div></div></div>';
						}

						var $item = $(html);
						$.data($item[0], 'data', data);
						River.river.isotope('insert', $item);
			    		break;
			    	case "facebook":
			    		var published = Utility.prettyDate(sourceData.published);
						
						if(sourceData.title != undefined) {
							var id = sourceData.id;
							var copy = Utility.truncateByWords(sourceData.title, 30);
							var image = $(sourceData.content).eq(1).children(':first').children().find('img').attr('src');
							var content = copy + '<img src="'+image+'" class="item-content-image" />';
							var html = '';
							var shareTwitter = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/tweet_button.html?url='+Utility.urlEncode(id)+'&amp;text='+Utility.urlEncode(Utility.stripTags(Utility.truncateByWords(sourceData.title, 20, false)))+'&amp;count=none" class="twitter-button"></iframe>';
							var shareGoogle = '<div class="google-button"><div class="g-plusone" data-size="medium" data-annotation="none" data-href="'+id+'"></div></div>';	
							var shareFacebook = '<div class="facebook-button"><iframe src="//www.facebook.com/plugins/like.php?href='+Utility.urlEncode(id)+'&amp;send=false&amp;layout=standard&amp;width=56&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:56px; height:35px;" allowTransparency="true"></iframe></div>';
							var shareHtml = shareTwitter + shareGoogle + shareFacebook;
							var data = {type: 'facebook', shareHtml: shareHtml, shareCount: 3, echoId: id};

							if(River.support3d == true) {
								var extraCss3Html = '<div class="side-3-css3"><div class="side-rollover"><p class="rollover-text">'+copy+'</p><p class="timestamp">'+published+'</p></div></div><div class="side-4-css3"><p>'+copy+'</p></div>';
								html = '<div class="bieber-container all facebook" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3"><p>'+copy+'</p></div><div class="side-2 side-2-css3"><div class="side-rollover"><p class="rollover-text">'+copy+'</p><p class="timestamp">'+published+'</p></div></div>'+extraCss3Html+'</div></div></div>';
							} else {
								html = '<div class="bieber-container all facebook"><div class="outter-container"><div class="inner-container"><div class="side-1"><p>'+copy+'</p></div><div class="side-2 nocss3d"><p class="rollover-text">'+copy+'</p><p class="timestamp">'+published+'</p></div></div></div></div>';
							}
							
							var $item = $(html);
							$.data($item[0], 'data', data);
							River.river.isotope('insert', $item);
						}
						
			    		break;
			    	case "news":
			    		var id = sourceData.id;
			    		var date = new Date(sourceData.published.replace(/-/g, '/').substring(0, sourceData.published.indexOf('T')));
			    		var day = date.getDate();
							day = (day < 10) ? '0'+day : day;
						var published = Utility.getTextMonth(date.getMonth(), false) + ' ' + day + ', ' + date.getFullYear();
						var newsIdPos = sourceData.id.indexOf('=');
						var newsId = sourceData.id.substring(newsIdPos + 1);
						var newsContent = sourceData.content;
						var newsTitle = sourceData.title.replace(' | News', '');
						var content = Utility.truncateByWords($(sourceData.content).remove('object').remove('img').text(), 30);
						content = content.replace(' | News', '</strong> ');
						content = '<strong class="news-title">' + content;
						var html = '';
						var shareTwitter = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/tweet_button.html?url='+Utility.urlEncode(id)+'&amp;text='+Utility.urlEncode(newsTitle)+'&amp;count=none" class="twitter-button"></iframe>';
						var shareGoogle = '<div class="google-button"><div class="g-plusone" data-size="medium" data-annotation="none" data-href="'+id+'"></div></div>';	
						var shareFacebook = '<div class="facebook-button"><iframe src="//www.facebook.com/plugins/like.php?href='+Utility.urlEncode(id)+'&amp;send=false&amp;layout=standard&amp;width=56&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:56px; height:35px;" allowTransparency="true"></iframe></div>';
						var sharePinterest = '';
						
						var shareCount = 3;
						
						//using original imageURL def from image section, will update when we change river
						var newsImageUrl = $(newsContent).children().find('img:first').attr('src');
						var newsImageClass = '';

						if(newsImageUrl == undefined) {
							newsImageClass = 'empty';
						} else {
							shareCount = 4;
							sharePinterest = '<a href="http://pinterest.com/pin/create/button/?url='+Utility.urlEncode(id)+'&media='+Utility.urlEncode(newsImageUrl)+'&description='+Utility.urlEncode(newsTitle)+'" class="pin-it-button" count-layout="horizontal" target="_blank"><img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
						}
						
						var shareHtml = shareTwitter + shareGoogle + shareFacebook + sharePinterest;
						var data = {type: 'news', content: newsContent, published: published, echoId: id, shareHtml: shareHtml, shareCount: shareCount};
						
						if(River.support3d == true) {
							var extraCss3Html = '<div class="side-3-css3"><div class="side-rollover"><p class="rollover-text">'+content+'</p><p class="timestamp">'+published+'</p></div></div><div class="side-4-css3"><div class="news-thumb ' +newsImageClass+'"><img src="'+newsImageUrl+'"/></div><p>'+content+'</p></div>';
							html = '<div class="bieber-container all news" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3"><div class="news-thumb ' +newsImageClass+'"><img src="'+newsImageUrl+'"/></div><p>'+content+'</p></div><div class="side-2 side-2-css3"><div class="side-rollover"><p class="rollover-text">'+content+'</p><p class="timestamp">'+published+'</p></div></div>'+extraCss3Html+'</div></div></div>';
						} else {
							html = '<div class="bieber-container all news"><div class="outter-container"><div class="inner-container"><div class="side-1"><div class="news-thumb ' +newsImageClass+'"><img src="'+newsImageUrl+'"/></div><p>'+content+'</p></div><div class="side-2 nocss3d"><p class="rollover-text">'+content+'</p><p class="timestamp">'+published+'</p></div></div></div></div>';
						}

						var $item = $(html);
						$.data($item[0], 'data', data);
						River.river.isotope('insert', $item);
			    		break;
						
			    	case "youtube":
			    		var id = sourceData.id;
			    		var published = Utility.prettyDate(sourceData.published);
						var videoId = sourceData.id.substr(sourceData.id.search("v=")+2);
						var shareTumblrCopy = 'Watch #JustinBieber\'s '+sourceData.title+' http://www.justinbiebermusic.com';
						var shareTwitterCopy = 'Watch @JustinBieber\'s '+sourceData.title+' http://www.justinbiebermusic.com';


						var videoEmbed = '<object width="600" height="315" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"><param name="SRC" value="http://youtube.com/v/'+videoId+'"><embed src="http://youtube.com/v/'+videoId+'" width="600" height="315"></embed></object>';
						var shareTwitter = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/tweet_button.html?url='+Utility.urlEncode(id)+'&amp;text='+Utility.urlEncode(shareTwitterCopy)+'&amp;count=none" class="twitter-button"></iframe>';
						var shareGoogle = '<div class="google-button"><div class="g-plusone" data-size="medium" data-annotation="none" data-href="'+id+'"></div></div>';	
						var shareFacebook = '<div class="facebook-button"><iframe src="//www.facebook.com/plugins/like.php?href='+Utility.urlEncode(id)+'&amp;send=false&amp;layout=standard&amp;width=56&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=35&amp;appId=100866110018302" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:56px; height:35px;" allowTransparency="true"></iframe></div>';
						var shareTumblr = '<a href="http://www.tumblr.com/share/video?embed='+Utility.urlEncode(videoEmbed)+'&caption='+Utility.urlEncode(shareCopy)+'" title="Share on Tumblr" target="_blank" style="display:inline-block; text-indent:-9999px; overflow:hidden; width:62px; height:20px; float: left; margin: 2px 0 0 7px; background:url(\'http://platform.tumblr.com/v1/share_2.png\') top left no-repeat transparent;">Share on Tumblr</a>';
						var shareHtml = shareTwitter + shareGoogle + shareFacebook + shareTumblr;
						var data = {type: 'video', title: sourceData.title, videoId: videoId, published: published, echoId: id, shareHtml: shareHtml, shareCount: 5};
						var html = '';

						if(River.support3d == true) {
							var extraCss3Html = '<div class="side-4-css3" style="background: url(http://i.ytimg.com/vi/'+videoId+'/0.jpg) no-repeat 50% 50%;"><div class="video-title">'+sourceData.title+'</div><div class="video-btn"></div></div><div class="side-3-css3" style="background: url(http://i.ytimg.com/vi/'+videoId+'/0.jpg) no-repeat 50% 50%;"><div class="video-title">'+sourceData.title+'</div><div class="side-rollover"><div class="video-btn-dark launchModal"></div><p class="timestamp">'+published+'</p></div></div>';
							html = '<div class="bieber-container all video" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3" style="background: url(http://i.ytimg.com/vi/'+videoId+'/0.jpg) no-repeat 50% 50%;"><div class="video-title">'+sourceData.title+'</div><div class="video-btn"></div></div><div class="side-2 side-2-css3" style="background: url(http://i.ytimg.com/vi/'+videoId+'/0.jpg) no-repeat 50% 50%;"><div class="video-title">'+sourceData.title+'</div><div class="side-rollover"><div class="video-btn-dark launchModal"></div><p class="timestamp">'+published+'</p></div></div>'+extraCss3Html+'</div></div></div>';
						} else {
							html = '<div class="bieber-container all video"><div class="outter-container"><div class="inner-container"><div class="side-1" style="background: url(http://i.ytimg.com/vi/'+videoId+'/0.jpg) no-repeat 50% 50%;"><div class="video-title">'+sourceData.title+'</div><div class="video-btn-dark"></div></div><div class="side-2 nocss3d" style="background: url(http://i.ytimg.com/vi/'+videoId+'/0.jpg) no-repeat 50% 50%;"><div class="video-title">'+sourceData.title+'</div><div class="side-rollover"><div class="video-btn-dark launchModal"></div><p class="timestamp">'+published+'</p></div></div></div></div></div>';
						}	

						var $item = $(html);
						$.data($item[0], 'data', data);
						River.river.isotope('insert', $item);
			    		break;
			    	case "photos":
			    		var id = sourceData.id;
			    		var published = Utility.prettyDate(sourceData.published);
						var imageUrl = $(sourceData.content).eq(1).children().children().children().attr('data-src-full');

						if(imageUrl == undefined) {
							imageUrl = $(sourceData.content).eq(1).children().children().children().attr('src');
						}

						// We'll eventually find this damn image...
						if(imageUrl == undefined) {
							imageUrl = $(sourceData.content).eq(2).children().find('p:last').children().find('img').attr('src');
						}

						var extraPos = imageUrl.indexOf(':full');
				
						if(extraPos > 0) {
							imageUrl = imageUrl.substring(0, extraPos);	
						}
						
						var extraPos = imageUrl.indexOf(':image');
				
						if(extraPos > 0) {
							imageUrl = imageUrl.substring(0, extraPos);	
						}
						

						if(imageUrl.indexOf('itunes_preview') === -1) {
 							var shareCopy = 'Love this photo from @JustinBieber!';
							var shareHtml = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/tweet_button.html?url='+Utility.urlEncode(id)+'&amp;text='+Utility.urlEncode(shareCopy)+'&amp;count=none" class="twitter-button"></iframe>';
							shareHtml += '<a href="http://pinterest.com/pin/create/button/?url='+Utility.urlEncode(id)+'&media='+Utility.urlEncode(imageUrl)+'&description='+Utility.urlEncode(shareCopy)+'" class="pin-it-button" count-layout="horizontal" target="_blank"><img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
							
							var data = {type: 'image', image: imageUrl, published: published, title: sourceData.title, echoId: id, shareHtml: shareHtml, shareCount: 2};

							if(River.support3d == true) {
								var extraCss3Html = '<div class="side-3-css3" style="background: url('+imageUrl+') no-repeat 50% 15%;"><div class="side-rollover"><a href="#" class="view-larger launchModal"></a><p class="timestamp">'+published+'</p></div></div><div class="side-4-css3" style="background: url('+imageUrl+') no-repeat 50% 15%;"></div>';
								html = '<div class="bieber-container all photo" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3" style="background: url('+imageUrl+') no-repeat 50% 15%;"></div><div class="side-2 side-2-css3" style="background: url('+imageUrl+') no-repeat 50% 15%;"><div class="side-rollover"><a href="#" class="view-larger launchModal"></a><p class="timestamp">'+published+'</p></div></div>'+extraCss3Html+'</div></div></div>';
							} else {
								html = '<div class="bieber-container all photo"><div class="outter-container"><div class="inner-container"><div class="side-1" style="background: url('+imageUrl+') no-repeat 50% 15%;"></div><div class="side-2 nocss3d" style="background: url('+imageUrl+') no-repeat 50% 15%;"><div class="side-rollover"><a href="#" class="view-larger launchModal"></a><p class="timestamp">'+published+'</p></div></div></div></div></div>';
							} 

				    		
						 	var $item = $(html);
				    		$.data($item[0], 'data', data);
				    		River.river.isotope('insert', $item);
				    	}
			    		break;
						
						
						
						
						
						
						
					case "fan":
						var actor = sourceData.actor;
						sourceData = sourceData.object;
			    		var id = sourceData.id;
			    		var published = Utility.prettyDate(sourceData.published);

						if(sourceData.content.indexOf("<br>") != -1) {
							var contentData = sourceData.content.split("<br>");
							var fullContent = contentData[1];
							var media = $.trim(contentData[0]);
						} else {
							var media = '';
							var fullContent = sourceData.content;
						}
						
						var img = '';
						
						try {
							if($(media).is('img'))
								img = media;
							else if($(media).is('iframe'))
								img = '<img src="assets/fan_feed_video.png" alt="fan_feed_video" width="200" height="230" />'
						} catch (e) {
							img = '';
						}
						
						var content = Utility.truncateByWords(fullContent, 30);
						
						var likes = '';
						if(sourceData.likes)
							likes = sourceData.likes.length;
													
						var shareCopy = 'Love this photo from @JustinBieber!';
						var shareHtml = '';//<iframe allowtransparency="true" frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/tweet_button.html?url='+Utility.urlEncode(id)+'&amp;text='+Utility.urlEncode(shareCopy)+'&amp;count=none" class="twitter-button"></iframe>';
						var data = {type: 'fan', image: media, published: published, content: fullContent, echoId: id, actor: actor, shareHtml: shareHtml, shareCount: 0, likes: sourceData.likes};
					
						if(River.support3d == true) {

							var extraCss3Html = '<div class="side-3-css3"><div class="side-rollover"><p class="rollover-text">'+content+'</p></a><p class="timestamp">'+published+'</p><a class="vote-btn">'+likes+'</a></div></div><div class="side-4-css3"><div class="thumb">'+img+'</div><p class="rollover-text">'+content+'</p><a class="vote-btn">'+likes+'</a></div>';
							html = '<div class="bieber-container fan" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3"><div class="thumb">'+img+'</div><p class="rollover-text">'+content+'</p><a class="vote-btn">'+likes+'</a></div><div class="side-2 side-2-css3"><div class="side-rollover"><p class="rollover-text">'+content+'</p><p class="timestamp">'+published+'</p><a class="vote-btn">'+likes+'</a></div></div>'+extraCss3Html+'</div></div></div>';
							
						} else {
							html = '<div class="bieber-container fan"><div class="outter-container"><div class="inner-container"><div class="side-1" >'+content+'<a class="vote-btn">'+likes+'</a></div><div class="side-2 nocss3d" ><div class="side-rollover"><p>'+content+'</p><p class="timestamp">'+published+'</p><a class="vote-btn">'+likes+'</a></div></div></div></div></div>';
						}
						
						/*if(River.support3d == true) {
							var extraCss3Html = '<div class="side-3-css3"><div class="side-rollover"><p class="rollover-text">'+content+'</p><p class="timestamp">'+published+'</p></div></div><div class="side-4-css3"><div class="news-thumb ' +newsImageClass+'"><img src="'+newsImageUrl+'"/></div><p>'+content+'</p></div>';
							html = '<div class="bieber-container fan" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3"><div class="news-thumb ' +newsImageClass+'"><img src="'+newsImageUrl+'"/></div><p>'+content+'</p></div><div class="side-2 side-2-css3"><div class="side-rollover"><p class="rollover-text">'+content+'</p><p class="timestamp">'+published+'</p></div></div>'+extraCss3Html+'</div></div></div>';
						} else {
							html = '<div class="bieber-container fan"><div class="outter-container"><div class="inner-container"><div class="side-1"><div class="news-thumb ' +newsImageClass+'"><img src="'+newsImageUrl+'"/></div><p>'+content+'</p></div><div class="side-2 nocss3d"><p class="rollover-text">'+content+'</p><p class="timestamp">'+published+'</p></div></div></div></div>';
						} */

						
						var $item = $(html);
						$('iframe', $item).replaceWith('');
						$.data($item[0], 'data', data);
						River.river.isotope('insert', $item);
						
						if(likes == '')
							likes = 0;
						
						var thisFanLikes = {
							likes: likes,
							el: $item
						};
						
						//If less than 5 liked posts, automatically add this to the list.
						if(River.topFiveFan.length < 5 && likes) {
							River.topFiveFan.push(thisFanLikes);
							thisFanLikes.el.addClass('all');
						} else if(likes) {
							
							//Cycle through each of the topFiveFans, and find the one with the least likes.
							var minLikes = River.topFiveFan[0];
							for(var fanpost = 1; fanpost < River.topFiveFan.length; fanpost++) {
								if(River.topFiveFan[fanpost].likes < minLikes.likes) {
									minLikes = River.topFiveFan[fanpost];
									minLikes.fanpost = fanpost;
								}
							}
							
							//Compare thisFanLikes to minLikes.likes
							if(thisFanLikes.likes > minLikes.likes) {
								minLikes.el.removeClass('all');
								thisFanLikes.el.addClass('all');
								River.topFiveFan[minLikes.fanpost] = thisFanLikes;
							}
						}
						
					break;
					
					
					
					
					
					
					
					
					
					case "store":
					
						var id = sourceData.id;
			    		var published = Utility.prettyDate(sourceData.published);
					
						var content = $('<div>'+sourceData.content+'</div>');
						var buyUrl = content.find('a').attr('href');
						var buyBttn = $('<div><a href="'+buyUrl+'" target="_blank" class="buy-bttn">Buy Now</a></div>');
						var imageUrl = content.find('img').remove().attr('src');
						
						var media='test media';
						var fullContent = 'test full content';
					
						var data = {type: 'store', image: media, content: fullContent, echoId: id, shareHtml: '', shareCount: 0};
					
						if(River.support3d == true) {
							var extraCss3Html = '<div class="side-3-css3"><div class="side-rollover">'+content.html()+buyBttn.html()+'</div></div><div class="side-4-css3" style="background-image: url('+imageUrl+');"></div>';
							html = '<div class="bieber-container all store" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3" style="background-image: url('+imageUrl+');"></div><div class="side-2 side-2-css3" ><div class="side-rollover">'+content.html()+buyBttn.html()+'</div></div>'+extraCss3Html+'</div></div></div>';
						} else {
							html = '<div class="bieber-container all store"><div class="outter-container"><div class="inner-container"><div class="side-1" style="background-image: url('+imageUrl+');"></div><div class="side-2 nocss3d" style="background-image: url('+imageUrl+');"><div class="side-rollover">'+content.html()+buyBttn.html()+'</div></div></div></div></div>';
						} 
						
						var $item = $(html);
						$('a', $item).attr('target', '_blank');
						$.data($item[0], 'data', data);
						River.river.isotope('insert', $item);

					break;
					
					
						
						
						
						
						
						
						
			    	case 'gifs':
			    		var shareHtml = '<a href="http://www.tumblr.com/share/photo?source='+Utility.urlEncode(sourceData.src)+'&caption='+Utility.urlEncode('Love this animated GIF of #JustinBieber! http://justinbiebermusic.com')+'&clickthru='+Utility.urlEncode('http://justinbiebermusic.com')+'" target="_blank" title="Share on Tumblr" style="display:inline-block; text-indent:-9999px; overflow:hidden; width:62px; height:20px; background:url(\'http://platform.tumblr.com/v1/share_2.png\') top left no-repeat transparent;">Share on Tumblr</a>';
						var data = {shareHtml: shareHtml, shareCount: 1};

			    		if(River.support3d == true) {
			    			var extraCss3Html = (River.support3d == true) ? '<div class="side-3-css3" style="background: url(\''+sourceData.src+'\') no-repeat 50% 15%;"><div class="side-rollover"></div></div><div class="side-4-css3" style="background: url(\''+sourceData.src+'\') no-repeat 50% 15%;"></div><div class="side-5-css3"><div class="social-icons"><a href="#" class="icon-facebook"></a><a href="#" class="icon-twitter"></a><a href="#" class="icon-info"></a></div><p class="timestamp">'+sourceData.src+published+'</p></div><div class="side-6-css3"><div class="social-icons"><a href="#" class="icon-facebook"></a><a href="#" class="icon-twitter"></a><a href="#" class="icon-info"></a></div></div>' : '';
			    			html = '<div class="bieber-container all photo gif" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3" style="background: url(\''+sourceData.src+'\') no-repeat 50% 15%;"></div><div class="side-2 side-2-css3" style="background: url(\''+sourceData.src+'\') no-repeat 50% 15%;"><div class="side-rollover"></div></div>'+extraCss3Html+'</div></div></div>';
			    		} else {
			    			html = '<div class="bieber-container all photo gif"><div class="outter-container"><div class="inner-container"><div class="side-1" style="background: url(\''+sourceData.src+'\') no-repeat 50% 15%;"></div><div class="side-2 nocss3d" style="background: url(\''+sourceData.src+'\') no-repeat 50% 15%;"><div class="side-rollover"></div></div></div></div></div>';
			    		}
						
			    		var $item = $(html);
			    		$.data($item[0], 'data', data);
			    		River.river.isotope('insert', $item);
			    		break;
						
						
			    	case 'albums':
			    		var html = '';
			    		var shareHtml = '<div class="album-share-links">';

			    		if(sourceData.amazon != '') {
			    			shareHtml += '<a href="'+sourceData.amazon+'" target="_blank"><img src="assets/link_amazon.png" /></a>';
			    		}

			    		if(sourceData.itunes != '') {
			    			shareHtml += '<a href="'+sourceData.itunes+'" target="_blank"><img src="assets/link_itunes.png" /></a>';
			    		}

			    		if(sourceData.rdio != '') {
			    			shareHtml += '<a href="'+sourceData.rdio+'" target="_blank"><img src="assets/link_rdio.png" /></a>';
			    		}

			    		if(sourceData.spotify != '') {
			    			shareHtml += '<a href="'+sourceData.spotify+'" target="_blank"><img src="assets/link_spotify.png" /></a>';
			    		}

			    		if(sourceData.walmart != '') {
			    			shareHtml += '<a href="'+sourceData.walmart+'" target="_blank"><img src="assets/link_walmart.png" /></a>';
			    		}
						
						var localShareHtml = '<a href="#" class="item-read-more launchModal">Read More</a>';

			    		shareHtml += '</div>';

			    		if(River.support3d == true) {
			    			var extraCss3Html = '<div class="side-3-css3" style="background: url(assets/albums/'+sourceData.cover+'.jpg) no-repeat 50% 15%;"><div class="side-rollover"><div class="album-title launchModal">'+sourceData.title+'</div>'+localShareHtml+'</div></div><div class="side-4-css3" style="background: url(assets/albums/'+sourceData.cover+'.jpg) no-repeat 50% 15%;"></div>';
			    			html = '<div class="bieber-container all albums shared" data-deg="0"><div class="river-share-buttons"></div><div class="outter-container"><div class="inner-container inner-container-css3"><div class="side-1 side-1-css3" style="background: url(assets/albums/'+sourceData.cover+'.jpg) no-repeat 50% 15%;"></div><div class="side-2 side-2-css3" style="background: url(assets/albums/'+sourceData.cover+'.jpg) no-repeat 50% 15%;"><div class="side-rollover"><div class="album-title launchModal">'+sourceData.title+'</div>'+localShareHtml+'</div></div>'+extraCss3Html+'</div></div></div>';
			    		} else {
			    			html = '<div class="bieber-container all albums shared"><div class="outter-container"><div class="inner-container"><div class="side-1" style="background: url(assets/albums/'+sourceData.cover+'.jpg) no-repeat 50% 15%;"></div><div class="side-2 nocss3d" style="background: url(assets/albums/'+sourceData.cover+'.jpg) no-repeat 50% 15%;"><div class="side-rollover"><div class="album-title launchModal">'+sourceData.title+'</div>'+shareHtml+'</div></div></div></div></div>';
			    		}
						
			    		var $item = $(html);
						
						var data = {type: 'album', id: sourceData.itunesId, cover: sourceData.cover, title: sourceData.title, shareHtml: shareHtml };
						$.data($item[0], 'data', data);
						
			    		River.river.isotope('insert', $item);

			    		break;
			    }
				
				if (i%River.sourceOrder.length == (River.sourceOrder.length - 1)) {
			        River.shuffle(River.sourceOrder);
			    }
			}
		}
	
		River.outerContainer = $('.bieber-container');
		River.outerContainer.unbind('mouseenter').unbind('mouseleave');
		River.outerContainer.bind('mouseenter', this.onMouseOverItem).bind('mouseleave', this.onMouseOutItem);
		$('.twitter .inner-container .side-2 a, .twitter .inner-container .side-3-css3 a, .facebook .inner-container .side-2 a, .facebook .inner-container .side-3-css3 a').attr('target', '_blank');

		// Replace twitter and news URL text with [link]
		var anchorTags = $('.twitter p a, .news p a');
		Utility.concatUrlFromAnchorTags(anchorTags);
		River.sourceOffset++;
	},

	show: function() {
		document.location.hash = '/home';
		River.allowResize = true;
		River.showBackToTop = true;
		River.riverInner.css({
			left: 0
		});
		
		River.filterContainer.css({
			right: River.riverWidth+'px'
		});

		River.riverContainer.addClass('active-window');
		River.onResizeRiver('doit');
		Utility.gaTrackEvent('River', 'Open');
	},

	hide: function() {
		River.riverContainer.removeClass('active-window');
		River.riverInner.css({left: River.riverWidth+'px'});
		River.filterContainer.css({right: '-48px'});
		Utility.gaTrackEvent('River', 'Close');
	},

	deepLink: function(hash) {
		hash = hash.replace('#/', '');

		switch(hash) {
			case 'gallery':
				River.onClickRiverTab();
			break;
			case 'events':
				River.onClickNav('eventsPage');
			break;
			case 'chat':
				River.onClickNav('chatPage');
			break;
			case 'about':
				River.onClickNav('aboutPage');
			break;
		}

		if(hash.indexOf('news') != -1) {
			var id = hash.substr(5);
			for(var i=0; i<River.rJb.data.length; i++) {
				for(var ii=0; ii<River.rJb.data[i].length; ii++) {
					var sourceData = River.rJb.data[i][ii].object;
					var newsIdPos = sourceData.id.indexOf('=');
					var newsId = sourceData.id.substring(newsIdPos + 1);

					if(newsId == id) {
						var date = new Date(sourceData.published);
		    			var day = date.getDate();
						day = (day < 10) ? '0'+day : day;
						var published = Utility.getTextMonth(date.getMonth(), false) + ' ' + day + ', ' + date.getFullYear();
						var newsContent = sourceData.content;
						var data = {type: 'news', content: newsContent, published: published, echoId: sourceData.id};
						//River.hide();
						River.onFilterItems(null, $('.navigation .news a').get(0));
						ContentPanel.show(data);
					}
				}
			}
		}

		if(hash.indexOf('video') != -1) {
			var id = hash.substr(6);
			for(var i=0; i<River.rYt.data.length; i++) {
				for(var ii=0; ii<River.rYt.data[i].length; ii++) {
					var sourceData = River.rYt.data[i][ii].object;
					var videoId = sourceData.id.substr(sourceData.id.search("v=")+2);

					if(videoId == id) {
						var published = Utility.prettyDate(sourceData.published);
						var videoId = sourceData.id.substr(sourceData.id.search("v=")+2);
						var data = {type: 'video', title: sourceData.title, videoId: videoId, published: published, echoId: sourceData.id};
						River.hide();
						ContentPanel.show(data);
					}
				}
			}
		}
	},


	launchModal: function(event) {
		var dataContainer = $(this).parents('.bieber-container')[0];
		var data = $.data(dataContainer, 'data');
		//River.hide();
		ContentPanel.show(data);

		event.preventDefault();
	},
	
	onClickVote: function(event) {
		var dataContainer = $(this).parents('.bieber-container')[0];
		var data = $.data(dataContainer, 'data');
		
		if(typeof Echo.Vars.users == 'undefined') {
			alert('Please login to vote.');
		} else {
			
			if(data.likes) {
				for(var i = 0; i < data.likes.length; i++) {
					if(data.likes[i].actor.id == Echo.Vars.users['dev.umg'].data.id) {
						alert('You already voted on this item!');
						return;
					}
				}
			} else {
				data.likes = [];	
			}
			
			$.get("http://apps.echoenabled.com/v2/esp/activity", {
				appkey: 'dev.umg',
				content: $.object2JSON({verb: 'like', target:data.echoId}),
				sessionID: Echo.Vars.users['dev.umg'].data.sessionID
			}, function() {
				var count = parseInt($('.vote-btn', dataContainer).html());
				
				data.likes.push({actor:{
					id: Echo.Vars.users['dev.umg'].data.id,
					title: Echo.Vars.users['dev.umg'].data.name,
					avator: Echo.Vars.users['dev.umg'].data.avatar
				}});
				
				if(isNaN(count))
					count = 1;
				else
					count ++
					
				$('.vote-btn', dataContainer).html(count);
			}, "jsonp"); 
		}
	},

	onBackToTop: function(event) {
		$('#riverInner').animate({ scrollTop: 0 }, 800);

		event.preventDefault();
	},

	onYoutubeScrollUp: function(event) {
		var positionTop = parseInt($('#youtubeVideos').css('top'));

		if(positionTop < 0) {
			positionTop += 85;

			if(!$('#youtubeVideos').is(':animated')) {
				$('#youtubeVideos').animate({top: positionTop+'px'}, 250);
			}
		}

		event.preventDefault();
	},

	onYoutubeScrollDown: function(event) {
		var positionTop = parseInt($('#youtubeVideos').css('top'));

		if(positionTop > -(River.youtubeHeight - 85)) {
			positionTop -= 85;

			if(!$('#youtubeVideos').is(':animated')) {
				$('#youtubeVideos').animate({top: positionTop+'px'}, 400);
			}
		}

		event.preventDefault();
	},

	onMouseMove: function(event) {
		River.mousePos.x = event.clientX;
		River.mousePos.y = event.clientY;
	},

	onResizeRiver: function(event) {
		var windowWidth = $(document).width();
		var windowHeight = $(window).height();

		if(typeof(event) == 'string' && event == 'init') {
			windowWidth = windowWidth - 15; // Compensate for the width of scroll bar on page load
		}

		var usableWidth = windowWidth * .48;
		var items = Math.floor(usableWidth / 182);
		var newWidth = (items * 182) + (items * 12) + 28 + 18; // 182 = item width, 12 = margin between items, 28 = padding in river
		River.riverWidth = newWidth;

		if(River.currentItems != items || event == 'doit' || event == 'init') {
			if(River.allowResize == true) {
				switch(items) {
					case 3:
						$('#ads').show();
						$('.ads').width(571);
						$('.right').hide();
						break;
					case 4:
						$('#ads').show();
						$('.ads').width(763);
						$('.right').show().removeClass("wide");
						break;
					case 5:
						$('#ads').show();
						$('.ads').width(958);
						$('.right').show().addClass("wide");
						break;
					case 6:
					case 7:
					case 8:
						break;
					case 9:
						break;
					default:
						$('#ads').show();
						$('.ads').width(571);
						$('.right').hide();
						break;
				}

				River.riverContainer.css({width: newWidth+'px'});
				River.filterContainer.css({right: newWidth+'px'});
			}

			River.currentItems = items;
			Events.onResizeWidth(newWidth);
			About.onResizeWidth(newWidth);
			Chat.onResizeWidth(newWidth);
			setTimeout(function() {
				River.river.isotope('reLayout');
			}, 850);
		}
		
		if(ContentPanel.active || event == 'doit' || event == 'init')
			ContentPanel.onResizeWidth(newWidth);

		//$('#footer').css({width: windowWidth - newWidth + 'px'});
		Gallery.onresize(windowHeight - 126); // Compensate 64px for the top fixed header
		ContentPanel.onResizeHeight(windowHeight - 126);
		Events.onResizeHeight(windowHeight - 126);
		About.onResizeHeight(windowHeight - 126);
		Chat.onResizeHeight(windowHeight - 126);
		if(Cube.initialized){
			Cube.onResizeWidth(newWidth);
			Cube.onResizeHeight(windowHeight - 126);
		}
		River.riverInner.height(windowHeight - 166);
	},

	onScrollToLoadMore: function(event) {
		if (River.endOfLine) return;

		var scrollTop = $('#riverInner').scrollTop();

		if(scrollTop >= ($('#river').height() - $(window).height()) && !$('#albumFilter').hasClass('active')) {
			if (!River.killScroll) {
				River.killScroll = true;
				var rnd=Math.floor(Math.random()*11)
				$('#loadMore').html('<img src="assets/loader.gif?r='+rnd+'" />');
				River.loadAllTheThings();
			}
		}

		if(River.showBackToTop == true) {
			if(scrollTop > 200) {
				River.backToTop.fadeIn(200);
			} else {
				River.backToTop.fadeOut(200);
			}
		}
	},

	onFilterItems: function(event, element) {
		
		if(typeof element == 'undefined')
			element = this;
		
		var filterName = '.'+element.parentNode.className; 
		var trackFilterName = $(element).next().children().text();
		Utility.gaTrackEvent('River', 'Filter', trackFilterName);
		
		if(event !== null)
			ContentPanel.hide();
		
		if(!$(element).hasClass('active')) {
			$('#river').isotope({
				filter: filterName
			});
			Utility.log('Filtering by: ' + filterName);

			if(filterName == '.albums') {
				if(River.support3d == true) {
					$('.filterMusic').parents('.nav-inner').addClass('active');
				} else {
					$('.filterMusic').parent().addClass('active');
				}

				$('#loadMore').hide();
			} else {
				$('.nav-inner').removeClass('active');
				$('.nav-side2').removeClass('active');
				$('#loadMore').show();
			}
			
			if(filterName == '.fan') {
				$('#fanSubmit').slideDown();
			} else {
				$('#fanSubmit').slideUp();
			}

			if($('#navigation').children().find('.active').length > 0) {
				var oldNav = $('#navigation').children().find('.active')[0];
				var className = oldNav.parentNode.className; 
				Header.animateNavRollout($(oldNav), className);
				$(oldNav).removeClass('active');
			}

			$(element).addClass('active');

			$('#riverInner').animate({ scrollTop: 0 }, 800);

			// Wait for filtering animation to finish and get the height of river
			setTimeout(function() {
				var riverHeight = $('#river').height();
				var windowHeight = $('#riverInner').height();
				
				if(riverHeight <= windowHeight && filterName != '.albums') {
					River.loadAllTheThings();
					
				}
			}, 900);
		}
		
		if(event)
			event.preventDefault();
	},

	onClickRiverTab: function(event) {
		River.hide();
		Gallery.show();
		ContentPanel.hide();
		document.location.hash = '/gallery';

		if(event != undefined) {
			event.preventDefault();
		}
	},

	onClickNav: function(event) {
		// Check to see which window (gallery or river) we have to hide to display Events page
		var className = (this.className != undefined) ? this.className : event;
		var el = (typeof(event) == 'object') ? this : '.'+className;
		$('.nav-inner').removeClass('active');
		$('.nav-side2').removeClass('active');

		switch(className) {
			case 'eventsPage':
				River.hideActivePanel();
				Events.show();
				document.location.hash = '/events';

				if(River.support3d == true) {
					$(el).parents('.nav-inner').addClass('active');
				} else {
					$(el).parent().addClass('active');
				}
			break;
			case 'aboutPage':
				River.hideActivePanel();
				About.show();
				document.location.hash = '/about';

				if(River.support3d == true) {
					$(el).parents('.nav-inner').addClass('active');
				} else {
					$(el).parent().addClass('active');
				}
			break;
			case 'chatPage':
				River.hideActivePanel();
				Chat.show();
				document.location.hash = '/chat';

				if(River.support3d == true) {
					$(el).parents('.nav-inner').addClass('active');
				} else {
					$(el).parent().addClass('active');
				}
			break;
			case 'filterMusic':
				if(!$('#riverContainer').hasClass('active-window')) {
					River.hideActivePanel();
					River.show();
				}

				if(!$('#albumFilter').hasClass('active')) {
					$('#river').isotope({
						filter: '.albums'
					});	

					if($('#navigation').children().find('.active').length > 0) {
						var oldNav = $('#navigation').children().find('.active')[0];
						var className = oldNav.parentNode.className; 
						Header.animateNavRollout($(oldNav), className);
						$(oldNav).removeClass('active');
					}

					$('#albumFilter').addClass('active').css({backgroundPosition: '-1107px -304px'});
				}

				if(River.support3d == true) {
					$(this).parents('.nav-inner').addClass('active');
				} else {
					$(this).parent().addClass('active');
				}
			break;
		}

		if(typeof(event) == 'object') {
			event.preventDefault();
		}
	},

	hideActivePanel: function() {
		var activeWindow = $('.active-window').attr('id');

		switch(activeWindow) {
			case 'riverContainer':
				River.hide();	
			break;
			case 'sidebar-container':
				Gallery.hide();
			break;
			case 'chatPanelContainer':
				Chat.hide();
			break;
			case 'eventPanelContainer':
				Events.hide();
			break;
			case 'aboutPanelContainer':
				About.hide();
			break;
			case 'contentPanelContainer':
				ContentPanel.hide();
			break;
			case 'cubePanelContainer':
				Cube.hide();
			break;
		}
	},

	onMouseOverItem: function(event) {
		var $self = $(this);
		var data = $.data($self[0], 'data');

		if(!$self.hasClass('shared')) {
			River.rolloverTimer = setTimeout(function() {
				var shareHtml = '';

				switch(data.type) {
					case 'twitter':
						shareHtml += '<a href="'+data.echoId+'" target="_blank" class="item-read-more externalShareLink" data-type="twitter">Go to Tweet</a>';
					break;
					case 'facebook':
						shareHtml += '<a href="'+data.echoId+'" target="_blank" class="item-read-more externalShareLink" data-type="facebook">Go to Post</a>';
					break;
					case 'news':
					case 'fan':
						shareHtml += '<a href="#" class="item-read-more launchModal">Read More</a>';
					break;
				}

				shareHtml += '<div class="social-icons-'+data.shareCount+'">'+data.shareHtml+'</div>';

				if(River.support3d == true) {
					if(data.type == 'twitter' || data.type == 'facebook' || data.type == 'news') {
						$self.find('.river-share-buttons').append(shareHtml).addClass('has-read-more');
					} else {
						$self.find('.river-share-buttons').append(shareHtml);
					}
				} else {
					$self.children().find('.side-2').append(shareHtml);
				}

				River.loadGoogleButtons();
				$self.addClass('shared');
			}, 800);
		} else {
			if(River.support3d == true) {
				River.rolloverTimer = setTimeout(function() {
					$self.find('.river-share-buttons').fadeIn(400);
				}, 400);
			} 
		}
		
		//easter egg
		if($self.hasClass('photo')) {
			if(!River.easterEgg.discovered){
				if(River.easterEgg.timeoutID < 0){
					River.easterEgg.timeoutID = setTimeout(River.clearEasterEggTimeout, 500);
				}


				if(River.easterEgg.rolloverCount++ > 3){
					River.showEasterEgg();
				}
			}
		}else if(!River.easterEgg.discovered){
			River.clearEasterEggTimeout();
		}
		//end easter egg

		if(River.support3d == true) {
			var itemOffset = $self.offset();
			var translateZ = 0;
			var rotate = '';
			var itemRotation = parseInt($self.attr('data-deg'));

			if($self.hasClass('video')) {				
				if(River.mousePos.y < event.clientY) {
					itemRotation -= 90;
					rotate = 'translateZ(-106.5px) rotateX('+itemRotation+'deg)';
				} else {
					itemRotation += 90;
					rotate = 'translateZ(-106.6px) rotateX('+itemRotation+'deg)';
				}
	 		} else {
				
				if(River.mousePos.x < event.clientX) {
					itemRotation += 90;
					rotate = 'translateZ(-91px) rotateY('+itemRotation+'deg)';
				} else {
					itemRotation -= 90;
					rotate = 'translateZ(-91px) rotateY('+itemRotation+'deg)';
				}
			}

			$self.attr('data-deg', itemRotation);
			$self.children().find('.inner-container').css({
				webkitTransform: rotate,
				MozTransform: rotate
			});
		} else {
			if(!$self.children().children().find('.side-2').is(':animated')) {
				$self.children().children().find('.side-2').fadeIn(250);
			}
		}
	},

	onMouseOutItem: function(event) {
		var $self = $(this);

		clearTimeout(River.rolloverTimer);
		River.rolloverTimer = 0;

		if($self.hasClass('shared')) {
			if(River.support3d == true) {
				$self.find('.river-share-buttons').hide();
			}
		}

		if(River.support3d == true) {
			var translateZ = 0;
			var itemRotation = parseInt($self.attr('data-deg'));
			var rotate = '';
			var itemOffset = $self.offset();

			if($self.hasClass('video')) {
				if(event.clientY < itemOffset.top) {
					itemRotation += 90;
					rotate = 'translateZ(-106.5px) rotateX('+itemRotation+'deg)';
				} else {
					itemRotation -= 90;
					rotate = 'translateZ(-106.5px) rotateX('+itemRotation+'deg)';
				}
			} else {				
				if(event.clientX < itemOffset.left) {
					itemRotation -= 90;
					rotate = 'translateZ(-91px) rotateY('+itemRotation+'deg)';
				} else {
					itemRotation += 90;
					rotate = 'translateZ(-91px) rotateY('+itemRotation+'deg)';
				}
			}

			$self.attr('data-deg', itemRotation);
			$self.children().find('.inner-container').css({
				webkitTransform: rotate,
				MozTransform: rotate
			});
		} else {
			$self.children().children().find('.side-2').fadeOut(250);
		}
	},

	trackExternalNavLink: function(event) {
		var type = (this.getAttribute('data-type') != null) ? this.getAttribute('data-type') : '';

		if(type == 'twitter') {
			Utility.gaTrackEvent('River', 'View', 'Tweet');
		} else if (type == 'facebook') {
			Utility.gaTrackEvent('River', 'View', 'Facebook Post');
		} else {
			var navLinkName = this.innerHTML;
			Utility.gaTrackEvent('External Link', 'Click', navLinkName);
		}

		window.open(this.href);
		event.preventDefault();
	},

	openSocialBar: function(event) {

		$('#ucid_bar').animate({top: '0'});

		event.preventDefault();
	},

	//easterEgg
	clearEasterEggTimeout: function () {
		clearTimeout(River.easterEgg.timeoutID);
		River.easterEgg.timeoutID = -1;
		River.easterEgg.rolloverCount = 0;
	},
	
	showEasterEgg: function () {
		Gallery.showItem(Gallery.easterEgg, true);
		River.clearEasterEggTimeout();
		River.easterEgg.discovered = true;
	},

	loadGoogleButtons: function() {
		var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
	    po.src = 'https://apis.google.com/js/plusone.js';
	    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
	}
};

$(document).ready($.proxy(River.init, River));